package com.ljqc.sbom.management.exception.handler;

import com.ljqc.sbom.management.bean.Result;
import com.ljqc.sbom.management.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


/**
 * GlobalExceptionHandler
 */
@Slf4j
@Order(128)
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * Handle exception http entity.
     *
     * @param e the e
     * @return the http entity
     */
    @ExceptionHandler(BusinessException.class)
    public HttpEntity<?> handleBusinessException(final BusinessException e) {
        // 业务异常 只需要warning即可
        StackTraceElement traceElement = e.getStackTrace()[0];
        log.warn("Caught business exception, message: {}, method: {}, line : {}",
                e.getMessage(), traceElement.getClassName() + "." + traceElement.getMethodName(), traceElement.getLineNumber());
        return new ResponseEntity<>(Result.fail(e.getCode(), e.getMessage()), e.getStatus());
    }

    /**
     * Handle exception http entity.
     *
     * @param e the e
     * @return the http entity
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(final HttpServletRequest request, final Exception e) {
        log.error("Caught exception", e);
        return Result.fail(500, "内部错误");
    }
}
